const mongoose = require('mongoose');
const bcrypt = require('bcryptjs');
const config = require('../config');
const { User, FieldType } = require('../models');

// 字段类型初始数据
const fieldTypes = [
  {
    type: "dateTimeGroup",
    name: "日期时间组",
    category: "input",
    description: "日期和时间输入组合",
    icon: "calendar",
    isSystem: true,
    valueSchema: {
      type: "object",
      properties: {
        year: { type: "number", minimum: 1900, maximum: 2100 },
        month: { type: "number", minimum: 1, maximum: 12 },
        day: { type: "number", minimum: 1, maximum: 31 },
        hour: { type: "number", minimum: 0, maximum: 23 },
        minute: { type: "number", minimum: 0, maximum: 59 },
        alignment: { type: "string", enum: ["left", "center", "right"] }
      },
      required: ["year", "month", "day"]
    },
    defaultConfig: {
      value: {
        year: null,
        month: null,
        day: null,
        hour: null,
        minute: null,
        alignment: "left"
      }
    },
    renderConfig: {
      component: "DateTimeGroupRender",
      props: {},
      events: ["change"]
    }
  },
  {
    type: "radioWithInput",
    name: "单选带输入",
    category: "selection",
    description: "单选选项，部分选项可以输入额外信息",
    icon: "radio",
    isSystem: true,
    valueSchema: {
      type: "object",
      properties: {
        label: { type: "string" },
        options: {
          type: "array",
          items: {
            type: "object",
            properties: {
              value: { type: "string" },
              label: { type: "string" },
              showInput: { type: "boolean" },
              inputLabel: { type: "string" },
              inputType: { type: "string", enum: ["text", "number", "textarea"] }
            },
            required: ["value", "label"]
          }
        },
        selected: { type: "string" },
        inputValue: { type: "string" },
        alignment: { type: "string", enum: ["left", "center", "right"] }
      },
      required: ["label", "options"]
    },
    defaultConfig: {
      value: {
        label: "",
        options: [],
        selected: "",
        inputValue: "",
        alignment: "left"
      }
    },
    renderConfig: {
      component: "RadioWithInputRender",
      props: {},
      events: ["change", "input"]
    }
  },
  {
    type: "signatureDateGroup",
    name: "签字日期组",
    category: "composite",
    description: "签字和日期的组合输入",
    icon: "signature",
    isSystem: true,
    valueSchema: {
      type: "object",
      properties: {
        signature: { type: "string" },
        date: {
          type: "object",
          properties: {
            year: { type: "number" },
            month: { type: "number", minimum: 1, maximum: 12 },
            day: { type: "number", minimum: 1, maximum: 31 }
          }
        },
        alignment: { type: "string", enum: ["left", "center", "right"] }
      }
    },
    defaultConfig: {
      value: {
        signature: "",
        date: { year: null, month: null, day: null },
        alignment: "left"
      }
    },
    renderConfig: {
      component: "SignatureDateGroupRender",
      props: {},
      events: ["change"]
    }
  },
  {
    type: "criteriaTable",
    name: "标准表格",
    category: "composite",
    description: "可配置列的标准表格",
    icon: "table",
    isSystem: true,
    valueSchema: {
      type: "object",
      properties: {
        title: { type: "string" },
        columns: {
          type: "array",
          items: {
            type: "object",
            properties: {
              id: { type: "string" },
              title: { type: "string" },
              type: { type: "string", enum: ["text", "number", "radio", "checkbox", "textarea"] },
              width: { type: "string" },
              options: {
                type: "array",
                items: {
                  type: "object",
                  properties: {
                    value: { type: "string" },
                    label: { type: "string" }
                  }
                }
              }
            },
            required: ["id", "title", "type"]
          }
        },
        rows: {
          type: "array",
          items: { type: "object" }
        },
        note: { type: "string" }
      },
      required: ["title", "columns"]
    },
    defaultConfig: {
      value: {
        title: "",
        columns: [],
        rows: [],
        note: ""
      }
    },
    renderConfig: {
      component: "CriteriaTableRender",
      props: {},
      events: ["change"]
    }
  },
  {
    type: "radioWithTextarea",
    name: "单选带文本框",
    category: "selection",
    description: "单选选项，选择某项后显示文本框",
    icon: "radio-text",
    isSystem: true,
    valueSchema: {
      type: "object",
      properties: {
        label: { type: "string" },
        selected: { type: "string", enum: ["有", "无"] },
        textareaValue: { type: "string" },
        alignment: { type: "string", enum: ["left", "center", "right"] }
      }
    },
    defaultConfig: {
      value: {
        label: "",
        selected: "",
        textareaValue: "",
        alignment: "left"
      }
    },
    renderConfig: {
      component: "RadioWithTextareaRender",
      props: {},
      events: ["change"]
    }
  },
  {
    type: "textareaField",
    name: "文本域字段",
    category: "input",
    description: "多行文本输入框",
    icon: "textarea",
    isSystem: true,
    valueSchema: {
      type: "object",
      properties: {
        label: { type: "string" },
        value: { type: "string" },
        placeholder: { type: "string" },
        maxLength: { type: "number" },
        rows: { type: "number", minimum: 1, maximum: 20 },
        alignment: { type: "string", enum: ["left", "center", "right"] }
      },
      required: ["label"]
    },
    defaultConfig: {
      value: {
        label: "",
        value: "",
        placeholder: "",
        maxLength: 1000,
        rows: 3,
        alignment: "left"
      }
    },
    renderConfig: {
      component: "TextareaFieldRender",
      props: {},
      events: ["change", "blur"]
    }
  }
];

async function initDatabase() {
  try {
    console.log('正在连接数据库...');
    await mongoose.connect(config.mongodb.uri);
    console.log('数据库连接成功');

    // 清空现有数据（开发环境）
    if (config.nodeEnv === 'development') {
      console.log('清空现有数据...');
      await User.deleteMany({});
      await FieldType.deleteMany({});
    }

    // 创建管理员用户
    console.log('创建管理员用户...');
    const adminUser = new User({
      username: 'admin',
      email: 'admin@example.com',
      password: 'admin123',
      role: 'admin',
      profile: {
        firstName: '管理员',
        lastName: '系统'
      }
    });
    await adminUser.save();
    console.log('管理员用户创建成功');

    // 初始化字段类型
    console.log('初始化字段类型...');
    await FieldType.insertMany(fieldTypes);
    console.log(`${fieldTypes.length} 个字段类型初始化完成`);

    console.log('数据库初始化完成！');
    console.log(`
管理员账号信息：
用户名: admin
邮箱: admin@example.com
密码: admin123
    `);

  } catch (error) {
    console.error('数据库初始化失败:', error);
  } finally {
    await mongoose.connection.close();
    console.log('数据库连接已关闭');
    process.exit();
  }
}

// 运行初始化
initDatabase();